package leetcode.D300.T287;

class Solution {
    /*// 解法一：哈希法，空间复杂度比较高，但时间复杂度低，且不改变原数组
    public int findDuplicate(int[] nums) {
        int n = nums.length - 1;
        boolean[] table = new boolean[n];
        for (int num : nums) {
            if(table[num-1]) {
                return num;
            }
            table[num-1] = true;
        }
        return 0;
    }*/
    // 解法二：二分法，时间复杂度O(nlogn)，但是空间复杂度O(1)，也不改变原数组
    public int findDuplicate(int[] nums) {
        int n = nums.length - 1, left = 1, right = n;
        while(left < right) {
            int mid = (left + right) / 2;
            int count = 0;
            for(int i=0; i<nums.length; ++i) {
                if(nums[i] <= mid) {
                    count++;
                }
            }
            if(count <= mid) {
                left = mid + 1;
            } else {
                right = mid;
            }
        }
        return left;
    }
}